package org.bindinghelper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class CopyUtil {
    @SuppressWarnings("unchecked")
    public static <T> T getTypedCopy(T inputObject) throws Exception
    {
        return (T)getCopy(inputObject);
    }

    public static <T> T getCheckedCopy(T inputObject, Class<T> clazz) throws Exception
    {
        T ret = clazz.cast(getCopy(inputObject));
        return ret;
    }

    public static Object getCopy(Object inputObject) throws Exception
    {
        if(inputObject == null)
        {
            return null;
        }
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try
        {
            ByteArrayOutputStream bos =
                new ByteArrayOutputStream(); // A
            oos = new ObjectOutputStream(bos); // B
            // serialize and pass the object
            oos.writeObject(inputObject);   // C
            oos.flush();               // D
            ByteArrayInputStream bin =
                new ByteArrayInputStream(bos.toByteArray()); // E
            ois = new ObjectInputStream(bin);                  // F
            // return the new object
            return ois.readObject(); // G
        }
        finally
        {
        	if(oos != null)
        	{
        		oos.close();
        	}
        	if(ois != null)
        	{
        		ois.close();
        	}
        }
    }
}
